# 微信code换token
import requests
from config import BaseConfig

def wechat_code_to_token(code):
    # 构造请求URL
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code'.format(BaseConfig.WECHAT_APPID, BaseConfig.WECHAT_SECRET, code)
    try:
        # 发送GET请求
        response = requests.get(url)
        # 将响应转换为JSON格式
        data = response.json()
        # 判断是否包含openid字段
        if 'openid' in data:
            # 返回openid
            return data['openid']
        else:
            # 返回None
            return None
    except Exception as e:
        # 打印异常信息
        print(e)
        # 返回None
        return None

if __name__ == '__main__':
    print(wechat_code_to_token('021F9D9C7C9B9F8D9C7C9B9F8D9C7C9B9'))
